package service

import (
	"fmt"
	"os"
	"qld2devservice/cons"
	"qld2devservice/utils"
	"time"

	"github.com/go-redis/redis"
)

var (
	client       *redis.Client
	appNameRedis string
)

func RedisConnect() {
	var address string
	var password string
	var err error
	if cons.GRPC_TEST_MODE == cons.ENUM_SERVER {
		address, err = utils.Config.Get("redisAddress")
		password = "Quanlaidian@2019"
	} else if cons.GRPC_TEST_MODE == cons.ENUM_SERVER_TEST {
		address, err = utils.Config.Get("redisAddressTest")
		password = "Quanlaidian@2019"
	} else if cons.GRPC_TEST_MODE == cons.ENUM_LOCALHOST {
		address, err = utils.Config.Get("redisAddressLocalTest")
	}

	//fmt.Println("链接的redis地址123:", address)
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "conf get failed, err:", err.Error())
		os.Exit(1)
	}

	client = redis.NewClient(&redis.Options{
		Addr:     address,
		Password: password,
		DB:       cons.GRPC_TEST_MODE,
		//PoolSize: 50, // 连接池中的最大连接数

	})
	if _, err = client.Ping().Result(); err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "ping error", err.Error())
		os.Exit(0)
	}
	appNameRedis, err = utils.Config.Get("appname")
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, "conf get failed, err:", err.Error())
		os.Exit(1)
	}
	fmt.Println("链接的redis地址:", address)
}

func RedisSave(key, value string) error {
	return RedisSaveNoHeader("/"+appNameRedis+"/"+key, value)
}

func RedisSaveNoHeader(key, value string) error {
	if err2 := client.Set(key, value, 0).Err(); err2 != nil {
		err := utils.WrapError(err2, "RedisSaveNoHeader，redis保存数据失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisSaveNoHeader, err:", err.Error())
		return err
	}
	utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisSave", key, value)
	return nil
}

func RedisSaveExpiration(key, value string, expiration int64) (bool, error) {
	return RedisSaveExpirationNoHeader("/"+appNameRedis+"/"+key, value, expiration)
}

func RedisSaveExpirationNoHeader(key, value string, expiration int64) (firstSet bool, err error) {
	var err1 error
	if firstSet, err1 = RedisCheckNoHeader(key); err1 != nil {
		err = utils.WrapError(err1, "RedisSaveExpirationNoHeader，redis检查短期保存数据是否存在失败")
		utils.MyPrint(utils.PRINT_ERROR, err.Error())
		return
	}
	if err2 := client.Set(key, value, time.Duration(expiration)*time.Second).Err(); err2 != nil {
		err = utils.WrapError(err2, "RedisSaveExpirationNoHeader，redis短期保存数据失败")
		utils.MyPrint(utils.PRINT_ERROR, err.Error())
		return
	}
	utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisSaveExpiration", key, value)
	return
}

func RedisGet(key, defaultResult string) (string, error) {
	return RedisGetNoHeader("/"+appNameRedis+"/"+key, defaultResult)
}
func RedisGet1(key, defaultResult string) (string, error) {
	return RedisGetNoHeader1("/"+appNameRedis+"/"+key, defaultResult)
}

func RedisGetNoHeader(key, defaultResult string) (string, error) {
	if val, err2 := client.Get(key).Result(); err2 == redis.Nil {
		if err2 = RedisSaveNoHeader(key, defaultResult); err2 != nil {
			err := utils.WrapError(err2, "RedisGetNoHeader，redis初始化保持数据失败")
			utils.MyPrint(utils.PRINT_ERROR, err.Error())
			return "", err
		}
		utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisGet", key, " does not exist,set = ", defaultResult)
		return defaultResult, nil
	} else if err2 != nil {
		err := utils.WrapError(err2, "RedisGetNoHeader，redis获取数据失败")
		utils.MyPrint(utils.PRINT_ERROR, "missing_key", err.Error())
		return "", err
	} else {
		utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisGet", key, val)
		return val, nil
	}
}
func RedisGetNoHeader1(key, defaultResult string) (string, error) {
	if val, err2 := client.Get(key).Result(); err2 == redis.Nil {
		if err2 = RedisSaveNoHeader(key, defaultResult); err2 != nil {
			err := utils.WrapError(err2, "RedisGetNoHeader，redis初始化保持数据失败")
			utils.MyPrint(utils.PRINT_ERROR, err.Error())
			return "", err
		}
		utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisGet", key, " does not exist,set = ", defaultResult)
		return defaultResult, nil
	} else if err2 != nil {
		err := utils.WrapError(err2, "RedisGetNoHeader，redis获取数据失败")
		utils.MyPrint(utils.PRINT_ERROR, "missing_key", err.Error())
		return "", err
	} else {
		//utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisGet", key, val)
		return val, nil
	}
}

func RedisCheck(key string) (bool, error) {
	return RedisCheckNoHeader("/" + appNameRedis + "/" + key)
}

func RedisCheckNoHeader(key string) (bool, error) {
	if val, err2 := client.Get(key).Result(); err2 == redis.Nil {
		utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisCheckNoHeader", key, "false")
		return false, nil
	} else if err2 != nil {
		err := utils.WrapError(err2, "RedisCheckNoHeader，redis检查数据失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisCheckNoHeader, err:", err.Error())
		return false, err
	} else {
		utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisCheckNoHeader", key, "true", val)
		return true, nil
	}
}

func RedisDel(key string) error {
	if err2 := client.Del("/" + appNameRedis + "/" + key).Err(); err2 != nil {
		err := utils.WrapError(err2, "RedisDel，redis删除数据失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisDel, err:", err.Error())
		return err
	}
	utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisDel", "/"+appNameRedis+"/"+key)
	return nil
}

func RedisDelNoHeader(key string) error {
	if err2 := client.Del(key).Err(); err2 != nil {
		err := utils.WrapError(err2, "RedisDelNoHeader，redis删除数据失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisDel, err:", err.Error())
		return err
	}
	utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisDelNoHeader", key)
	return nil
}

func RedisKeyList(key string) (keys []string, err error) {
	var err1 error
	if keys, err1 = client.Keys("/" + appNameRedis + "/" + key + "*").Result(); err1 != nil {
		err = utils.WrapError(err1, "RedisKeyList，redis获取数据列表失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisKeyList, err:", err.Error())
		return
	} else {
		utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisGet", keys)
	}
	return
}

func RedisKeyListNoHeader(key string) (keys []string, err error) {
	var err1 error
	if keys, err1 = client.Keys("*" + key + "*").Result(); err1 != nil {
		err = utils.WrapError(err1, "RedisKeyListNoHeader，redis获取数据列表失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisKeyListNoHeader, err:", err.Error())
		return
	} else {
		//utils.MyPrintCaller(utils.PRINT_DEBUG, 3, "RedisKeyListNoHeader", key, keys)  //临时注释
	}
	return
}

func RedisGetKeyExpiration(key string) (time.Duration, error) {
	return RedisGetKeyExpirationNoHeader("/" + appNameRedis + "/" + key)
}

func RedisGetKeyExpirationNoHeader(key string) (time.Duration, error) {
	if val, err2 := client.TTL(key).Result(); err2 != nil {
		err := utils.WrapError(err2, "RedisGetKeyExpirationNoHeader，redis获取数据列表失败")
		utils.MyPrint(utils.PRINT_ERROR, "RedisGetKeyExpirationNoHeader, err:", err.Error())
		return 0, err
	} else {
		return val, nil
	}
}

func RedisMSetKeyListNoHeader(dataList []interface{}) {
	//utils.MyPrintCaller(utils.PRINT_DEBUG, 3, dataList)  //临时注释
	_, err := client.MSet(dataList...).Result()
	if err != nil {
		utils.MyPrint(utils.PRINT_ERROR, err.Error())
	}
}
func RedisSaveNoHeaderList(key, value string) error {
	if err2 := client.RPush(key, value).Err(); err2 != nil {
		err := utils.WrapError(err2, "RedisSaveNoHeader，redis保存数据失败")

		return err
	}
	utils.MyPrint(utils.PRINT_DEBUG, "Redisset", key, value)
	return nil
}
func RedisGetNoHeaderList(key string) ([]string, error) {
	if val, err2 := client.LRange(key, 0, -1).Result(); err2 == redis.Nil {

		return []string{}, nil
	} else if err2 != nil {

		return []string{}, nil
	} else {
		utils.MyPrint(utils.PRINT_DEBUG, "RedisGet", key)
		return val, nil
	}
}
